package com.qianniu.napi.admin.service.akka;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.LeagueMemberMapper;
import com.qianniu.napi.admin.mapper.StoreStatMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

public class FanliActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger("actorlog");

    private IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("userstatServiceImpl");
    private IFensService fensService = (IFensService) SpringUtil.getBean("fensServiceImpl");
    private IFenxiaoService fenxiaoService = (IFenxiaoService) SpringUtil.getBean("fenxiaoServiceImpl");
    private IFenxiaoFanService fenxiaoFanService = (IFenxiaoFanService) SpringUtil.getBean("fenxiaoFanServiceImpl");
    private IRedisService redisService = (IRedisService) SpringUtil.getBean("redisServiceImpl");
    private IJifenService jifenService = (IJifenService) SpringUtil.getBean("jifenServiceImpl");
    private IAccountService accountService = (IAccountService) SpringUtil.getBean("accountServiceImpl");
    private IXnbiService xnbiService = (IXnbiService) SpringUtil.getBean("xnbiServiceImpl");
    private IMerchantConfigService merchantConfigService = (IMerchantConfigService) SpringUtil.getBean("merchantConfigServiceImpl");
    private ISmslogService smslogService = (ISmslogService) SpringUtil.getBean("smslogServiceImpl");
    private IMerchantConfigService merchantConfigServiceImpl = (IMerchantConfigService) SpringUtil.getBean("merchantConfigServiceImpl");
    private IOrderService orderService = (IOrderService) SpringUtil.getBean("orderServiceImpl");
    private StoreStatMapper storeStatMapper = (StoreStatMapper) SpringUtil.getBean("storeStatMapper");
    private IGoodsService goodsService = (IGoodsService) SpringUtil.getBean("goodsServiceImpl");
    private IQnpay qnpay = (IQnpay) SpringUtil.getBean("qnpayImpl");
    private LeagueMemberMapper leagueMemberMapper = (LeagueMemberMapper) SpringUtil.getBean("leagueMemberMapper");
    private IMaccountService maccountService = (IMaccountService) SpringUtil.getBean("maccountServiceImpl");
    private IOrderGoodsService orderGoodsService = (IOrderGoodsService) SpringUtil.getBean("orderGoodsServiceImpl");
    private ICouponTplService couponTplService = (ICouponTplService) SpringUtil.getBean("couponTplServiceImpl");
    private IShareOpenService shareOpenService = (IShareOpenService) SpringUtil.getBean("shareOpenServiceImpl");
    private IFanConfigService fanConfigService = (IFanConfigService) SpringUtil.getBean("fanConfigServiceImpl");

    @Override
    public void onReceive(Object message) {

        String msg = message.toString();
        logger.debug("----------------FanliActor receive message:" + msg);

        // 格式 jytype + uid + amount + jptype
        // jytype jfhexiaook:积分核销 |orderpayok:订单支付 |rechargeok:积分核销
        String[] arr = msg.split("@");
//        if (arr.length < 4) return;
        try {
            String type = arr[0];
            String uid = arr[1];
            String amount = arr[2];
            String jptype = arr[3];
            logger.debug("----------------FanliActor start to process type=" + type + " uid=" + uid + " amount=" + amount + " jptype=" + jptype);
            switch (type) {
                case Constants.AKKA_FX_HEXIAO_OK:
                    hexiaoFan(Long.valueOf(uid), new BigDecimal(amount), Integer.valueOf(jptype));
                    break;
                case Constants.AKKA_FX_ORDER_PAY_OK:
                    processfan(Long.valueOf(uid), new Long(amount));
                    break;
                default:
                    return;
            }

        } catch (Exception e) {
            logger.error("----------------FanliActor error for", e);
        }

    }

    private void hexiaoFan(Long uid, BigDecimal amount, Integer jptype) {
        //1、判断是否支持返利
        //2、判断目标用户类型是否支持返利
        //3、判断推荐用户类型是否支持返利
        logger.info("------------------------------------------hexiaoFan uid=" + uid + ",amount=" + amount + ",jptype=" + jptype);
        User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,mid,mpid,utype,member_level memberLevel")
                .eq("id", uid));
        if (user == null) {
            logger.error("-----------hexiaoFan error for uid=[" + uid + "] unvalid");
            return;
        }
        logger.info("------------------------------------------hexiaoFan user=" + JSON.toJSONString(user) + ",amount=" + amount + ",jptype=" + jptype);

        MerchantConfig mconfig = redisService.getMconfig(user.getMpid());
        if (mconfig.getIsFenxiao() == null || mconfig.getIsFenxiao() != 1) {
            return;
        }
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("hytype", user.getUtype())
                .eq("mpid", user.getMpid()));
        logger.info("------------------------------------------hexiaoFan fenxiao=" + JSON.toJSONString(fenxiao));

        if (fenxiao == null) {
            return;
        }
        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {
            Fens fens = fensService.selectOne(new EntityWrapper<Fens>()
                    .eq("state", 1)
                    .eq("level_type", i)
                    .eq("uid", uid));
            if (fens == null) {
                logger.info("------------fens not exsist for uid=" + uid + " and level_type=1");
                continue;
            }
            Long puid = fens.getPuid();
            BigDecimal fxlv = getFenxiaoLv(fens, user, puid, i, FanType.xffan);
            if (fxlv == null) {
                continue;
            }
            logger.info("------------------------------------------fxlv=" + JSON.toJSONString(fxlv));
            BigDecimal fanli = amount.multiply(fxlv).divide(new BigDecimal(100));
            logger.info("------------------------------------------fanli=" + fanli.doubleValue());

            if (jptype.intValue() == XffanType.jifen.getVal()) {

                jifenService.addJifenFlow(puid, user.getMid(), user.getMpid(),
                        fanli, true, FantimeType.now.getVal(),
                        StringUtil.getSnNo("FL"), IotypeEnum.input, user.getUtype().intValue() == Hytype.merchant.getVal() ? JftypeEnum.shoufanli : JftypeEnum.xffanli, "", 0l);
            } else if (jptype.intValue() == XffanType.qian.getVal()) {

                accountService.addAccountFlow(puid, user.getMid(), user.getMpid(),
                        fanli, true, FantimeType.now.getVal(),
                        StringUtil.getSnNo("FL"), IotypeEnum.input, user.getUtype().intValue() == Hytype.merchant.getVal() ? XftypeEnum.shoufanli.shoufanli : XftypeEnum.xffanli, "", 0l);

            } else if (jptype.intValue() == XffanType.xnbi.getVal()) {

                xnbiService.addXnbiFlow(puid, user.getMid(), user.getMpid(),
                        fanli, true, FantimeType.now.getVal(),
                        StringUtil.getSnNo("FL"), IotypeEnum.input, user.getUtype().intValue() == Hytype.merchant.getVal() ? JftypeEnum.shoufanli : JftypeEnum.xffanli, "", 0l);
            }
        }
    }

    private void processfan(Long uid, Long oid) {
        //1、判断是否支持返利
        //2、判断目标用户类型是否支持返利
        //3、判断推荐用户类型是否支持返利

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm");
        logger.info(">>>>>>processfan oid:" + oid);

        //===============1、更新订单状态【状态类】===============
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("id", oid));
        logger.info(">>>>>>payConfirm order:" + JSON.toJSONString(order));

        Long mpid = order.getMpid();
        MerchantConfig mconfig = merchantConfigServiceImpl
                .selectOne(new EntityWrapper<MerchantConfig>().eq("mpid", mpid));

        order.setStatus(order.getGtype() == 1 && (order.getShipperMethod() != null && order.getShipperMethod() != 0) ?
                StatusEnum.forsend.getVal() : StatusEnum.receving.getVal());

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>order.getGtype()=" + order.getGtype());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>order.getJduid()=" + order.getJduid());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>order.getShipperMethod()=" + order.getShipperMethod());
        if (order.getGtype() == 3 && order.getJduid() != null &&
                order.getShipperMethod() != null && order.getShipperMethod() == 1) {
            order.setStatus(StatusEnum.forsend.getVal());
        }
        if (order.getXftype().intValue() == XftypeEnum.maidan.getVal() ||
                order.getXftype().intValue() == XftypeEnum.smaidan.getVal() ||
                order.getType().intValue() == YXType.dalibao.getVal()) {
            //大礼包默认虚拟商品
            order.setStatus(StatusEnum.finish.getVal());
        }

        order.setPaytime(new Date());
        order.setModifytime(new Date());
        order.setModifier(0l);

        Goods goods = goodsService.selectById(order.getGid());

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm updateOrderStatus order=" + JSON.toJSONString(order));
        qnpay.updateOrderStatus(order, order.getStatus());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm updateOrderStatus over");

        //==============更新商家概况==============
        if (order.getSid() != null && order.getType().intValue() > 0) {
            StoreStat storeStat = storeStatMapper.selectById(order.getSid());
            if (storeStat == null) {
                storeStat = new StoreStat();
                storeStat.setStoreid(order.getSid());
            }
            storeStat.setTotal(storeStat.getTotal().add(order.getRealpay()));
            storeStat.setMshoukuan(storeStat.getMshoukuan().add(order.getMinprice()));
            storeStat.setRenqi(storeStat.getRenqi() + 5);
            storeStat.setOrders(storeStat.getOrders() + 1);
            storeStat.setUsers(orderService.getHdCanyushu(order.getSid()));

            storeStat.setModifytime(new Date());
            storeStat.setMpid(order.getUid());
            storeStat.updateById();
        }
        //==============更新商家概况END==============

        //=============2、更新账户+账户流水表【账户+状态类】=============
        //=============2.1、用户积分抵扣确认核销

        //=============2.1.2、插入商家会员=============
        //联盟版商家会员买单
        insertMchmembers(order);

        //=============2.2、用户券抵扣确认核销，需要先插入会员再更新券

        //=============2.3、用户币抵扣确认核销一次只有一种

        //=============2.4、支付用户账户更新确认

        //=============2.5、用户交押金

        //=============2.6、实体店商家收款码收款（恰恰全积分支付）<特殊>

        //=============2.7、盟主(代理)优惠买单支付佣金入账==================

        //=============2.8、平台收款=====================

        //=============2.9、推荐会员佣金入账==================

        //=================营销活动状态处理=================

        //触发返佣时机
        Boolean ruzhang = goods == null ? false : goods.getFantimeType() == null ? goods.getFantimeType().intValue() == FantimeType.payok.getVal()
                : order.getFantimeType().intValue() == goods.getFantimeType().intValue();

        //=============3、佣金结算=============
        //=============3.1、处理自购奖励，触发点在支付成功之后

        if (goods != null &&
                FantimeType.payok.getVal() == goods.getFantimeType().intValue() &&
                (order.getFanjifen() != null && order.getFanjifen().doubleValue() > 0) ||
                (order.getFanqian() != null && order.getFanqian().doubleValue() > 0) ||
                (order.getFanbi() != null && order.getFanbi().doubleValue() > 0)) {
            zigouFan(order, FantimeType.payok.getVal(), ruzhang);
            //===待实现，自购返券

        } else {
            //全局定义的自购返属性定义
            //该逻辑废弃，统一在订单形成时计算
            //if (mconfig.getFantimeType() != null && mconfig.getFantimeType() == FantimeType.payok.getVal() &&
            //      ((order.getFanjifen() != null && order.getFanjifen().doubleValue() > 0) ||
            //              (order.getFanqian() != null && order.getFanqian().doubleValue() > 0) ||
            //              (order.getFanbi() != null && order.getFanbi().doubleValue() > 0))) {
            //                zigouFan(order);
            //}
        }

        //处理自购奖励返券
        //买单订单 goods==null
        //平台多商家版自购返，===待完善
        if (goods != null && goods.getZgfanType() != null &&goods.getZgfanType() != 0 && mconfig.getFantimeType() == FantimeType.payok.getVal()) {
            //处理自购返券===待观察触发返券时机
            if (goods != null && goods.getZgfanType() != null &&
                    goods.getZgfanType().intValue() == XffanType.quan.getVal()) zigouFanquan(order);
        }

        //=============End处理自购返End==========

        //=============3.2处理购买体验卡年卡类型

        //=============3.3检查购买会员商品
        logger.info("--------------------------------------start to check kaitong huiyuan");
        if (mconfig.getIsFenxiao() == 1 && order.getGid() != null) {
            logger.info("--------------------------------------start to check huiyuan 111");
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_HUIYUAN_SHENGJI + "@" + uid + "@hygoods" + "@" + order.getGid(), ActorRef.noSender());
        }

        //=============3.4推荐返佣《推荐者》
        //【普通分享奖励||多级分销返二选一，不能同时存在】
        //普通分享奖励，只返一级
        //非买单分享奖励，针对 gid>0
        //与订单一起生成，每笔订单对应一份奖励
        //order.getSharefan() >0  普通分享奖励模式
        //order.getFanqian()  >0  自购返
        logger.info("--------------------------------------start to check Sharefan");
        if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                && order.getXftype().intValue() != XftypeEnum.smaidan.getVal()) {
            logger.info("--------------------------------------payConfirm order.getSharefan()=" + order.getSharefan());
            shareFan(order);//商品+活动 gid>0
        }

        //=============3.5平台优惠券买单分佣《推荐者》
        //支付购买立即触发

        //=============3.6优惠买单付款至商家《商家》

        //=============3.7多级分销在fenxiaoFan处理《推荐者》
        //order.getFxe1()  >0  order.getFxe2()  >0
        logger.info("------------------------------------start to after Fenxiao");
        if (mconfig.getIsFenxiao() == 1 && order.getRealpay().doubleValue() > 0
                && order.getFxmode() != null && order.getFxmode() > 0) {
            logger.info("--------------------------------------start to check Fenxiao");
            fenxiaoFan(order);
        }

        logger.info(">>>>>>payConfirm qnpay.payPakect start");

        //=============3.8平台版付款至商家(收款)《商家》

        //=============3.9营销活动商品支付
        //营销活动统统针对商家
        //商家卖货，钱先到账至待入账金额里
        if (order.getType().intValue() >= 0 && order.getSid() != null && order.getSid().longValue() > 0
                && order.getMinprice() != null && order.getMinprice().doubleValue() >= 0) {//商家促销成本
            logger.info("-------------------------------payConfirm to muser account fanliing");
            //转账至商家
//            orderStorePay(order, ruzhang, order.getMinprice());
        }

        //=============4.0联盟收益
        if (order.getType().intValue() >= 0 && order.getSid() != null && order.getSid().longValue() > 0
                && order.getLmfan() != null && order.getLmfan().doubleValue() >= 0) {
            //联盟收益
            logger.info("-------------------------------payConfirm to orderAgentPay account fanliing");
            //转账至盟主佣金
//            orderAgentPay(order, ruzhang, order.getLmfan());
        }

        //=============4.1平台净收益
        if (order.getPtfan() != null && order.getPtfan().doubleValue() >= 0) {
            //平台净收益
            logger.info("-------------------------------payConfirm to orderPlatformPay account fanliing");
            //转账至盟主佣金
//            orderPlatformPay(order, ruzhang);
        }

        //=============End佣金结算=============

        //=============4、通知+提醒+人气+其他=============
        //=============4.1、订单短信提醒

        //=============4.2、如果是需要发货的订单，向商户端发货通知
        if (order.getGtype() == 1) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_NOTIFY + "@" + order.getId() + "@" + uid, ActorRef.noSender());
        }

        //=============4.3、处理店铺商家人气
        if (order.getSid() != null) {
            AkkaServer.system.actorOf(Props.create(StoreActor.class))
                    .tell(Constants.AKKA_MSG_STORE_ORDER + "@" + order.getSid(), ActorRef.noSender());
        }
        //=============END处理店铺商家人气

        logger.info("--------------------------------------payConfirm over");
    }

    private BigDecimal getFenxiaoLv(Fens fens, User user, Long puid, int level, FanType fanType) {

        User puser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,mid,mpid,utype,member_level memberLevel")
                .eq("id", puid));
        if (puser == null) {
            logger.error("------------------------puser not exsist for puid=" + puid);
            return null;
        }

        FenxiaoFan fenxiaoFan = fenxiaoFanService.selectOne(new EntityWrapper<FenxiaoFan>()
                .eq("thytype", puser.getUtype())
                .eq("hytype", user.getUtype())
                .eq("mpid", user.getMpid())
        );
        if (fenxiaoFan == null) {
            logger.error("------------------------fenxiaoFan not exsist for thytype=" + puser.getUtype() + " hytype=" + user.getUtype() + " mpid=" + user.getMpid());
            return null;
        }

        if (fanType == FanType.hyfan) {
            if (level == 1 && fenxiaoFan.getFan1() != null) return fenxiaoFan.getFan1();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan1() is null");
                return null;
            }
            if (level == 2 && fenxiaoFan.getFan2() != null) return fenxiaoFan.getFan2();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan2() is null");
                return null;
            }
            if (level == 3 && fenxiaoFan.getFan3() != null) return fenxiaoFan.getFan3();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan3() is null");
                return null;
            }
            if (level == 4 && fenxiaoFan.getFan4() != null) return fenxiaoFan.getFan4();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan4() is null");
                return null;
            }
            if (level == 5 && fenxiaoFan.getFan5() != null) return fenxiaoFan.getFan5();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan5() is null");
                return null;
            }
            if (level == 6 && fenxiaoFan.getFan6() != null) return fenxiaoFan.getFan6();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan6() is null");
                return null;
            }
            if (level == 7 && fenxiaoFan.getFan7() != null) return fenxiaoFan.getFan7();
            else if (fenxiaoFan.getFan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getFan7() is null");
                return null;
            }
        } else if (fanType == FanType.xffan) {
            if (level == 1 && fenxiaoFan.getXffan1() != null) return new BigDecimal(fenxiaoFan.getXffan1());
            else if (fenxiaoFan.getXffan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 2 && fenxiaoFan.getXffan2() != null) return new BigDecimal(fenxiaoFan.getXffan2());
            else if (fenxiaoFan.getXffan2() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 3 && fenxiaoFan.getXffan3() != null) return new BigDecimal(fenxiaoFan.getXffan3());
            else if (fenxiaoFan.getXffan3() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 4 && fenxiaoFan.getXffan4() != null) return new BigDecimal(fenxiaoFan.getXffan4());
            else if (fenxiaoFan.getXffan4() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 5 && fenxiaoFan.getXffan5() != null) return new BigDecimal(fenxiaoFan.getXffan5());
            else if (fenxiaoFan.getXffan5() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 6 && fenxiaoFan.getXffan6() != null) return new BigDecimal(fenxiaoFan.getXffan6());
            else if (fenxiaoFan.getXffan6() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
            if (level == 7 && fenxiaoFan.getXffan7() != null) return new BigDecimal(fenxiaoFan.getXffan7());
            else if (fenxiaoFan.getXffan7() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getXffan1() is null");
                return null;
            }
        } else if (fanType == FanType.shoufan) {
            if (level == 1 && fenxiaoFan.getShoufan1() != null) return new BigDecimal(fenxiaoFan.getShoufan1());
            else if (fenxiaoFan.getShoufan1() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan1() is null");
                return null;
            }
            if (level == 2 && fenxiaoFan.getShoufan2() != null) return new BigDecimal(fenxiaoFan.getShoufan2());
            else if (fenxiaoFan.getShoufan2() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan2() is null");
                return null;
            }
            if (level == 3 && fenxiaoFan.getShoufan3() != null) return new BigDecimal(fenxiaoFan.getShoufan3());
            else if (fenxiaoFan.getShoufan3() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan3() is null");
                return null;
            }
            if (level == 4 && fenxiaoFan.getShoufan4() != null) return new BigDecimal(fenxiaoFan.getShoufan4());
            else if (fenxiaoFan.getShoufan4() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan4() is null");
                return null;
            }
            if (level == 5 && fenxiaoFan.getShoufan5() != null) return new BigDecimal(fenxiaoFan.getShoufan5());
            else if (fenxiaoFan.getShoufan5() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan5() is null");
                return null;
            }
            if (level == 6 && fenxiaoFan.getShoufan6() != null) return new BigDecimal(fenxiaoFan.getShoufan6());
            else if (fenxiaoFan.getShoufan6() == null) {
                logger.error("------------------------fenxiaoFan.getShoufan6() is null");
                return null;
            }
            if (level == 7 && fenxiaoFan.getShoufan7() != null) return new BigDecimal(fenxiaoFan.getShoufan7());
            else if (fenxiaoFan.getShoufan7() == null) {
                logger.error("------------------------------------------------fenxiaoFan.getShoufan7() is null");
                return null;
            }
        }

        return new BigDecimal(0);
    }

    //优惠买单推荐奖励
    public void insertMchmembers(Order order) {
        if (order.getSid() == null || order.getLeagueid() == null) {
            logger.info("------------------------insertMchmembers order.getSid()=" + order.getSid());
            return;
        }

        User user = userService.selectById(order.getUid());
        logger.info("--------------------------------------insertMchmembers user=" + JSON.toJSONString(user));
        LeagueMember entity = new LeagueMember();
        entity.setSid(order.getSid());
        entity.setUid(order.getUid());
        LeagueMember leagueMember = leagueMemberMapper.selectOne(entity);
        //更新为客户
        if (leagueMember == null) {
            leagueMember = entity;
            leagueMember.setMid(order.getMid());
            leagueMember.setMpid(order.getMpid());
            leagueMember.setCreatetime(new Date());
            leagueMember.setPhone(user.getPhone() == null ? order.getPhone() : user.getPhone());
            leagueMember.setNickname(order.getLinkman());
            leagueMember.setHeadimg(order.getHeadimg() == null ? redisService.getUser(order.getUid()).getAvatarPic() : order.getHeadimg());
            leagueMember.setLeagueid(order.getLeagueid());
            leagueMember.setCreateday(DateUtil.getToday());
            leagueMember.setState(1);
            leagueMember.setUtype(Utype.kehu.getVal());
            leagueMember.setMlevel(-1);
            leagueMember.setSname(redisService.getStore(order.getSid()).getName());
            leagueMember.setLastxf(DateUtil.getToday());

            if (!Strings.isNullOrEmpty(order.getOri()))
                leagueMember.setShareid(ObjectUtil.orderFanuid(order.getOri()));
            if (leagueMember.getShareid() != null) {
                User shareuser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName")
                        .eq("id", leagueMember.getShareid()));
                leagueMember.setSharename(shareuser == null ? null : shareuser.getNickName());
            }
//            leagueMember.insert();
        } else if (leagueMember.getUtype().intValue() < Utype.kehu.getVal()) {
            leagueMember.setUtype(Utype.kehu.getVal());
        }
        leagueMember.insertOrUpdate();
    }

    //支付之后自购返处理逻辑
    public void zigouFan(Order order, Integer fantimeType, Boolean ruzhang) {

        logger.info("------------------------------------------------------zigouFan come");
        //返现用户
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        logger.info("-----------------zigouFan mpid=" + mpid);

        User user = userService.selectById(uid);
        if (user == null) {
            logger.info("------------------------zigouFan user is null for uid=" + uid);
            return;
        }

        //秒到+非秒到账
        BigDecimal bi = order.getFanbi();
        BigDecimal jifen = order.getFanjifen();
        BigDecimal qian = order.getFanqian();

        logger.info("--------------------------------------zigouFan start jifen=" + jifen);
        logger.info("--------------------------------------zigouFan start qian=" + qian);
        logger.info("--------------------------------------zigouFan start bi=" + bi);

        MerchantConfig mconfig = redisService.getMconfig(mpid);

        //mconfig.getIsMiaotui() 该属性针对现金返佣来说
        //mconfig.getIsAutofan() 该属性针对现金返佣来说
        //直接入账触发点 1：支付成功后；2：确认收货|扫码核销后；3：确认后7天到账&
        //否则先放入待返利中。。。
        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;

        if (jifen != null && jifen.doubleValue() > 0)
            jffanyong(user, jifen, XffanType.jifen.getVal(), order.getOrderNo(), ruzhang, JftypeEnum.xffanli);

        if (qian != null && qian.doubleValue() > 0)
            fanyong(user, qian, XffanType.qian.getVal(), fantimeType, order, ruzhang, nowfan, XftypeEnum.xffanli);
        if (bi != null && bi.doubleValue() > 0)
            fanyong(user, bi, XffanType.xnbi.getVal(), fantimeType, order, ruzhang, nowfan, XftypeEnum.xffanli);

        logger.info("------------------------------------------------zigouFan over");
    }

    //返积分入账（都是首次）
    private void jffanyong(User user, BigDecimal fxe, Integer fantype, String sn, Boolean ruzhang, JftypeEnum jftypeEnum) {

        MerchantConfig mconfig = redisService.getMconfig(user.getMpid());
        Integer fantime = mconfig.getFantimeType();
        if (fantype == XffanType.jifen.getVal()) {
            //积分入账，除了现金返利都及时入账
            addJifenFlow(user, fxe, ruzhang, fantime, sn, IotypeEnum.input, jftypeEnum, "用户分享返积分结算");
        }
    }

    //返佣金入账（都是首次）
    private void fanyong(User user, BigDecimal fxe, Integer fantype, Integer fantime, Order order, Boolean ruzhang, Boolean nowfan, XftypeEnum xftypeEnum) {

        Map<String, Object> paymap = new HashMap<String, Object>();
        MerchantApp mapp = redisService.getMApp(user.getMpid());
        if (fantype == XffanType.qian.getVal()) {
            //现金很特殊，区分不同时刻返佣金，先入账
            //商家出账记录，对于商家发生实际现金变动时，才会生成记录
            addAccountFlow(user, fxe, ruzhang, fantime, order, IotypeEnum.input, xftypeEnum);
            if (nowfan) {
                paymap = qnpay.payPakect(user.getMpid(), mapp.getAppid(), user, fxe, "佣金奖励", "127.0.0.1");
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //秒到账成功
                    addMaccountFlow(user, fxe, order.getOrderNo(), IotypeEnum.output, xftypeEnum, order.getTransactionId());
                    //奖励佣金直接发放
                    addAccountAutoFanFlow(user, fxe, fantime, order, IotypeEnum.output, xftypeEnum.autofanli, paymap.get("payment_no").toString());
                }
            }
        } else if (fantype == XffanType.quan.getVal() && nowfan) {//返券
            //待完善

        } else if (fantype == XffanType.xnbi.getVal() && nowfan) {//返币
            addXnbiFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, xftypeEnum, xftypeEnum.getName());

        } else if (fantype == XffanType.jifen.getVal() && nowfan) {
            //返积分
            addJifenFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, JftypeEnum.share, xftypeEnum.getName());
        }
    }

    private void addXnbiFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                             String sn, IotypeEnum iotype, XftypeEnum xftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        XnbiFlow xflow = new XnbiFlow();
        xflow.setConfirmDate(new Date());
        xflow.setCreatetime(new Date());
        xflow.setIotype(iotype.getVal());
        xflow.setIsConfirm(1);
        xflow.setJftype(xftype.getVal());
        xflow.setFantimeType(fantimeType);//===待实现

        xflow.setUid(uid);
        xflow.setMid(mid);
        xflow.setMpid(mpid);
        xflow.setRemark(remark);
        xflow.setNum(money);
        xflow.setSn(sn);
        xflow.setState(1);
        logger.debug("======xflow=" + xflow);
        xflow.insert();

        ruzhang = true;//及时入账

        Boolean flag = false;
        while (!flag) {
            Xnbi xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            if (xbi == null) xbi = initXnbi(uid, mid, mpid);
            Long version = xbi.getVersion();
            BigDecimal total = xbi.getTotal();
            BigDecimal fanliing = xbi.getFanliing();

            if (ruzhang) xbi.setTotal(iotype.getVal() == 1 ? total.add(money) : total.subtract(money));
            else xbi.setFanliing(iotype.getVal() == 1 ? fanliing.add(money) : fanliing.subtract(money));

            xbi.setModifytime(new Date());
            xbi.setModifier(uid);
            xbi.setVersion(version + 1);
            //******* 更新账户表 ********
            flag = xnbiService.update(xbi, new EntityWrapper<Xnbi>().eq("uid", uid).eq("version", version));
            logger.debug(">>>xnbiService.update flag=" + flag);
        }
    }

    //自动发放佣金，不走总账户
    //总账户不增加，可用账户不增加，累计佣金增加
    private void addAccountAutoFanFlow(User user, BigDecimal money, Integer fantimeType,
                                       Order order, IotypeEnum iotype, XftypeEnum xftype, String paymentno) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(new BigDecimal(0));
        af.setDikou(new BigDecimal(0));
        af.setRealpay(money);//实际提现
        af.setTotal(money);

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = initAccount(uid, mid, mpid);
        }
        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : order.getPhone());

        af.setSn(order.getOrderNo());
        af.setTransactionid(paymentno);
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setXftypename(xftype.getName());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setState(1);
        af.setIsConfirm(-1);
        af.setRuzhang(0);
        af.setTradetime(new Date());
        af.setCreatetime(af.getTradetime());
        af.setRemark(xftype.getName());

        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());

        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));

            Long version = act.getVersion();
            BigDecimal fanli = act.getFanli();

            naccount.setFanli(fanli.add(af.getRealpay()));

            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            af.setIsConfirm(1);
            af.setRuzhang(0);//只有延时佣金【需要核销或者需要确认订单的】才有 ruzhang=1
            af.setConfirmDate(new Date());
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }

    //积分及时入账
    private void addJifenFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                              String sn, IotypeEnum iotype, JftypeEnum jftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        JifenFlow jf = new JifenFlow();
        //*******  客户消耗  *******
        jf.setNum(money);
        jf.setSn(sn);//抵扣积分时 = 订单号
        jf.setIotype(iotype.getVal());//积分消费
        jf.setJftype(jftype.getVal());//积分消费
        jf.setFantimeType(fantimeType);
        jf.setCreatetime(new Date());
        jf.setUid(uid);
        jf.setMid(mid);
        jf.setMpid(mpid);
        jf.setRemark(jftype.getName());
        jf.setIsConfirm(1);
        jf.setConfirmDate(new Date());
        jf.setState(1);
        jf.insert();

        ruzhang = true;//积分及时入账,不在区分支付、核销、7天后入账

        Boolean flag = false;
        while (!flag) {
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            if (jifen == null) jifen = initJifen(uid, mid, mpid);

            long v = jifen.getVersion();
            BigDecimal total = iotype.getVal() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum());
            BigDecimal fanliing = iotype.getVal() == 1 ? jifen.getFanliing().add(jf.getNum()) : jifen.getFanliing().subtract(jf.getNum());

            if (ruzhang) jifen.setTotal(total);
            else jifen.setFanliing(fanliing);

            jifen.setVersion(jifen.getVersion() + 1);
            jifen.setModifytime(new Date());
            jifen.setModifier(uid);

            flag = jifenService.update(jifen, new EntityWrapper<Jifen>().eq("version", v).eq("uid", uid));
            logger.debug(">>>at jifenService update=" + flag);
        }
    }

    //返佣流水,iotype==1
    private void addAccountFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                                Order order, IotypeEnum iotype, XftypeEnum xftype) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(money);
        af.setDikou(new BigDecimal(0));//总营销金额 130
        af.setRealpay(new BigDecimal(0));//总价200 实付100
        af.setTotal(af.getAmount());

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = initAccount(uid, mid, mpid);
        }
        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : null);

        af.setSn(order.getOrderNo());
        af.setTransactionid(order.getTransactionId());
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setIsConfirm(-1);
        af.setRuzhang(-1);
        af.setState(1);
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setRemark(xftype.getName());
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);

        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));

            af.setIsConfirm(1);
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            af.setConfirmDate(new Date());

            Long version = act.getVersion();

            BigDecimal total = act.getTotal();
            BigDecimal amount = act.getAmount();

            BigDecimal unuseAmount = act.getUnuseAmount();
            BigDecimal fanliing = act.getFanliing();

            naccount.setTotal(iotype.getVal() == 1 ? total.add(af.getAmount()) : total.subtract(af.getAmount()));

            if (ruzhang) {
                af.setRuzhang(1);
                naccount.setAmount(iotype.getVal() == 1 ? amount.add(af.getAmount()) : amount.subtract(af.getAmount()));
            } else {
                naccount.setFanliing(iotype.getVal() == 1 ? fanliing.add(af.getAmount()) : fanliing.subtract(af.getAmount()));
                naccount.setUnuseAmount(iotype.getVal() == 1 ? unuseAmount.add(af.getAmount()) : unuseAmount);
            }
            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }


    private void addMaccountFlow(User user, BigDecimal money,
                                 String sn, IotypeEnum iotype, XftypeEnum xftype, String transactionId) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        MaccountFlow maf = new MaccountFlow();
        maf.setAmount(money);//实付100剩余20在一次充值时已更新
        maf.setMamount(new BigDecimal(0));//各种抵扣额度=商家的营销费用=总营销金额130

        maf.setUid(uid);
        maf.setMid(mid);
        maf.setMpid(mpid);

        maf.setCreatetime(new Date());
        maf.setTradetime(new Date());
        maf.setState(1);
        maf.setIsConfirm(-1);

        maf.setIotype(iotype.getVal());
        maf.setXftype(xftype.getVal());

        maf.setRemark(xftype.getName());
        maf.setSn(sn);
        maf.setTransactionid(transactionId);
        maf.insert();

        boolean flag = false;

        Maccount maccount = new Maccount();//企业付款成功
        while (!flag) {
            Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
            if (ma == null) {
                ma = initMaccount(uid, mid);
            }

            Long version = ma.getVersion();
            BigDecimal amount = ma.getAmount();
            BigDecimal total = ma.getTotal();
            BigDecimal sale = ma.getSaleAmount();
            BigDecimal market = ma.getMamount();

            maccount.setTotal(iotype.getVal() == -1 ? total.subtract(maf.getAmount()) : total.add(maf.getAmount()));       //总金额
            if (iotype.getVal() == 1) maccount.setSaleAmount(sale.add(maf.getAmount()));//累计销售额度
            maccount.setAmount(iotype.getVal() == -1 ? amount.subtract(maf.getAmount()) : amount.add(maf.getAmount()));    //可用余额
            maccount.setMamount(iotype.getVal() == -1 ? market.subtract(maf.getMamount()) : market.add(maf.getMamount()));  //营销总金额

            maccount.setModifytime(new Date());
            maccount.setModifier(uid);
            maccount.setVersion(version + 1);

            maf.setIsConfirm(1);
            maf.setLasttotal(ma.getTotal());
            maf.setConfirmDate(new Date());

            flag = maccountService.update(maccount, new EntityWrapper<Maccount>().eq("id", ma.getId()).eq("version", version));
            if (flag) maf.insertOrUpdate();
            logger.info("===========maccount flag=" + flag);
        }
    }


    public Account initAccount(Long uid, Long mid, Long mpid) {

        BigDecimal zero = new BigDecimal(0);

        Account act = new Account();
        act.setUid(uid);
        act.setMid(mid);
        act.setMpid(mpid);
        act.setCreatetime(new Date());
        act.setVersion(1l);


        User user = userService.selectById(uid);
        act.setNickname(user != null ? user.getNickName() : null);
        act.setHeadimg(user != null ? user.getAvatarPic() : null);
        act.setPhone(user != null ? user.getPhone() : null);

        act.setTotal(zero);
        act.setAmount(zero);
        act.setUnuseAmount(zero);
        act.setFanli(zero);
        act.setFanliing(zero);
        act.setFreeze(zero);
        act.setChargeAmount(zero);
        act.setLjxiaofei(zero);
        act.setMamount(zero);
        act.setWithdraw(zero);
        act.insert();
        return act;
    }

    public Maccount initMaccount(Long uid, Long mid) {

        BigDecimal zero = new BigDecimal(0);

        Maccount act = new Maccount();//初始化Maccount()
        act.setUid(uid);
        act.setMid(mid);
        act.setCreatetime(new Date());
        act.setVersion(1l);
        act.setState(1);

        act.setTotal(zero);
        act.setAmount(zero);
        act.setSaleAmount(zero);
        act.setMamount(zero);
        act.setUnuseAmount(zero);
        act.setFanliing(zero);
        act.setFreeze(zero);
        act.setChargeAmount(zero);
        act.setWithdraw(zero);
        act.setConsume(zero);
        //sms
        act.setSmsmout(new BigDecimal("80"));
        act.setSmsmoutTotal(new BigDecimal("80"));
        act.setSmsprice(new BigDecimal("0.08"));
        act.setSmstotal(1000);
        act.insert();

        logger.info("========initMaccount=" + JSON.toJSONString(act));
        return act;
    }


    public Jifen initJifen(Long uid, Long mid, Long mpid) {

        BigDecimal zero = new BigDecimal(0);
        Jifen act = new Jifen();
        act.setUid(uid);
        act.setMid(mid);
        act.setMpid(mpid);

        act.setCreatetime(new Date());
        act.setVersion(1l);
        act.setTotal(zero);
        act.setFanliing(zero);
        act.setState(1);
        act.insert();
        return act;
    }

    public Xnbi initXnbi(Long uid, Long mid, Long mpid) {

        BigDecimal zero = new BigDecimal(0);

        Xnbi act = new Xnbi();
        act.setUid(uid);
        act.setMid(mid);
        act.setMpid(mpid);

        act.setCreatetime(new Date());
        act.setVersion(1l);
        act.setTotal(zero);
        act.setFanliing(zero);
        act.setState(1);
        act.insert();
        return act;
    }


    /*
     * 计算分销额
     * 分销计算原则
     * 1.会员|代理人才有分销权利，普通用户没有
     * 2.普通用户对单个商品分享只能享受商品直推推广分佣（详见方法：shareFan）
     * 3.锁客（锁粉）模式下，上下级关系不变
     * 4.非锁客（锁粉）模式，粉丝变会员之前
     * 5.计算分销额，区别会员商品+普通商品
     * 6.会员商品直接单独购买，不能多商品组合订单
     * 7.普通商品可以组合订单(第一期分销只做总订单分销)
     * 8.第一期分销只做返现金
     * 9.分销价格计算依赖商品实际支付价格
     * 10.上级返佣人，必须是会员才能拥有分佣资格
     */
    public void fenxiaoFan(Order order) {
        logger.info("------------------------------------------------------start to come Fenxiao");

        //返现用户
        User user = null;
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        String sn = order.getOrderNo();

        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        List<OrderGoods> ogods = orderGoodsService.selectList(new EntityWrapper<OrderGoods>().eq("oid", order.getId()));

        List<FenxiaoFan> fxflist = fenxiaoFanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", mpid).orderBy("mlevel", true));

        if (fenxiao == null) {
            logger.debug("------------------------------------------------------fenxiao is null for mpid=" + mpid);
            return;
        }
        if (fxflist == null || fxflist.size() == 0) {
            logger.debug("------------------------------------------------------fxflist is null for mpid=" + mpid);
            return;
        }
        if (fxflist.size() != fenxiao.getFxlevel()) {
            logger.debug("------------------------------------------------------fxflist.size ne fenxiao.getFxlevel for mpid=" + mpid);
            return;
        }
        logger.info("------------------------------------------------------start to come Fenxiao jisuan");

        Map<String, FenxiaoFan> fxmap = new HashMap<String, FenxiaoFan>();
        for (FenxiaoFan item : fxflist) {
            fxmap.put("mlevel" + item.getMlevel(), item);
        }
        logger.info("------------------------------------------------------start to come Fenxiao fxmap=" + fxmap);


        int fxlevel = fenxiao.getFxlevel();
        Map<String, User> fxusermap = new HashMap<String, User>();
        Map<String, BigDecimal> fxemap = new HashMap<String, BigDecimal>();
        FenxiaoFan fxfan = null;
        int level = 0;

        BigDecimal jiandian = fenxiao.getJiandian();

        for (int i = 1; i <= fxlevel; i++) {
            Fens fens = fensService.selectOne(new EntityWrapper<Fens>()
                    .eq("uid", uid)            //当前成交用户
                    .eq("level_type", i)      //级别
                    .eq("status", 2)  //* 10.上级返佣人，必须是会员才能拥有分佣资格
            );

            if (fens == null) break;
            user = userService.selectById(fens.getPuid());
            if (user == null) continue;

            //======待完善
            //======如果上级会员中途失效，如何处理
            //======会员升级一般会有见点奖励，特定级别首领有
            level = user.getMemberLevel();
//           if (user.getIsMember() != 1) break;
            logger.info("-----------------------------------------------------start to come Fenxiao huiyuan order.getType()=" + order.getType() + " level=" + level);

            String key = "mlevel" + level;
            logger.info("------------------------------------------------------key=" + key);

            fxfan = fxmap.get(key);//会员对应级别
            logger.info("---------------------------------------------------------------------------fxfan from fxmap.get(key)=" + fxfan);
            if (fxfan == null) continue;//非会员 不参与分销
            logger.info("------------------------------------------------------start to come Fenxiao huiyuan order=" + order);

            if (order.getType() == YXType.hygoods.getVal()) {
                //会员订单商品，按照会员金额提成（因为升级会员的门槛是固定可控制的）
                //拉新会员有见点奖励
                //2  1  1
                //2  2  1
//               fxfan = fxmap.get("mlevel" + i);
                //计算分销额
                if (i == 1) {
                    order.setFxe1(order.getRealpay().multiply(fxfan.getFan1()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe1(order.getFxe2().add(jiandian));
                } else if (i == 2) {
                    order.setFxe2(order.getRealpay().multiply(fxfan.getFan2()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe2(order.getFxe2().add(jiandian));
                } else if (i == 3) {
                    order.setFxe3(order.getRealpay().multiply(fxfan.getFan3()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe3(order.getFxe3().add(jiandian));
                } else if (i == 4) {
                    order.setFxe4(order.getRealpay().multiply(fxfan.getFan4()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe4(order.getFxe4().add(jiandian));
                } else if (i == 5) {
                    order.setFxe5(order.getRealpay().multiply(fxfan.getFan5()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe5(order.getFxe5().add(jiandian));
                } else if (i == 6) {
                    order.setFxe6(order.getRealpay().multiply(fxfan.getFan6()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe6(order.getFxe6().add(jiandian));
                } else if (i == 7) {
                    order.setFxe7(order.getRealpay().multiply(fxfan.getFan7()).divide(new BigDecimal(100)));
                    if (fxfan.getIsJiandian() == 1) order.setFxe7(order.getFxe7().add(jiandian));
                }
                logger.info("------------------------------------------------------start to over Fenxiao huiyuan order=" + order);

            } else {
                //非会员商品|普通商品消费，，按照普通商品比例提成
                logger.info("----------------------------------------------------------------------------------------------------fxfan=" + fxfan);
                if (i == 1 && fxfan.getXffan1() != null) {
                    order.setFxe1(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan1())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe1(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan1())));
//                       }
//                   }
                } else if (i == 2 && fxfan.getXffan2() != null) {
                    order.setFxe2(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan2())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe2(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan2())));
//                       }
//                   }
                } else if (i == 3 && fxfan.getXffan3() != null) {
                    order.setFxe3(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan3())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe3(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan3())));
//                       }
//                   }
                } else if (i == 4 && fxfan.getXffan4() != null) {
                    order.setFxe4(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan4())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe4(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan4())));
//                       }
//                   }
                } else if (i == 5 && fxfan.getXffan5() != null) {
                    order.setFxe5(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan5())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe5(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan5())));
//                       }
//                   }
                } else if (i == 6 && fxfan.getXffan6() != null) {
                    order.setFxe6(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan6())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe6(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan6())));
//                       }
//                   }
                } else if (i == 7 && fxfan.getXffan7() != null) {
                    order.setFxe7(order.getRealpay().multiply(BigDecimal.valueOf(fxfan.getXffan7())).divide(new BigDecimal(100)));//实际支付金额*返点比例
//                   if (ogods != null && ogods.size() > 0) {
//                       for (int y = 0; y < ogods.size(); y++) {
//                           OrderGoods ogood = ogods.get(y);
//                           ogood.setFxe7(ogood.getSaleprice().multiply(new BigDecimal(ogood.getNumber())).multiply(BigDecimal.valueOf(fxfan.getXffan7())));
//                       }
//                   }
                }
            }

            //被奖励人
            fxusermap.put("fxuser" + i, user);
            logger.info("-----------------------------------------------------Fenxiao fxuser=" + user);

            if (i == 1 && order.getFxe1() != null && order.getFxe1().doubleValue() > 0) {
                fxemap.put("fxe" + i, order.getFxe1());
            } else if (i == 2 && order.getFxe2() != null && order.getFxe2().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe2());
            else if (i == 3 && order.getFxe3() != null && order.getFxe3().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe3());
            else if (i == 4 && order.getFxe4() != null && order.getFxe4().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe4());
            else if (i == 5 && order.getFxe5() != null && order.getFxe5().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe5());
            else if (i == 6 && order.getFxe6() != null && order.getFxe6().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe6());
            else if (i == 7 && order.getFxe7() != null && order.getFxe7().doubleValue() > 0)
                fxemap.put("fxe" + i, order.getFxe7());

        }

        logger.info("---------------------------------------------------start to come Fenxiao 2222");

        if (order.getFantimeType() == null) order.setFantimeType(mconfig.getFantimeType());
        order.updateById();
        //===待完善
//       if (ogods != null && ogods.size() > 0) {
//           for (int y = 0; y < ogods.size(); y++) {
//               OrderGoods ogood = ogods.get(y);
//               ogood.updateById();
//           }
//       }

        boolean ruzhang = mconfig.getFantimeType() == FantimeType.payok.getVal();
        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;
        FanConfig fconfig = redisService.getFanconfig(mpid);
        logger.info("----------------------------------------------------Fenxiao fanyong foreach");
        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {

            BigDecimal fxe = fxemap.get("fxe" + i);
            User fxuser = fxusermap.get("fxuser" + i);
            logger.info("----------------------------------------------------fenxiao fxe=" + fxe);
            logger.info("----------------------------------------------------fenxiao fxuser=" + fxuser);
            if (fxuser == null) break;
            //=========待完善
            fanyong(fxuser, fxe, fconfig.getMdfanType(), FantimeType.payok.getVal(), order, ruzhang, nowfan, XftypeEnum.fenxiaofan);
        }

        logger.info("----------------------------------------------------Fenxiao over");
    }


    //处理商品+活动订单直接推荐返利
    //该商品是非买单充值商品gtype>0
    //直推佣金先按照总订单，不分开计算
    //直推佣金计算=必须order.getSharefan()>0
    public void shareFan(Order order) {

        logger.info("----------------------------shareFan come");

        //返现用户
        Long mid = order.getMid();
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        Long gid = order.getGid();
        Long fanuid = order.getFanuid();
        logger.debug("---------------------------shareFan for fanuid=" + fanuid);
        logger.debug("---------------------------shareFan for order.getSharefan()=" + order.getSharefan());
        if (order.getSharefan() == null || order.getSharefan().doubleValue() <= 0) {
            return;
        }

        //此方法只计算gid>0,买单充值不在该逻辑
        if (order.getGid() == null) {
            logger.info("--------------------------------------shareFan return order.getGid()==null");
            return;
        }
        //--------1、获取佣金人优先级从（推荐人+推荐商品）第一
        //--------2、获取佣金人优先级从转发记录
        if (fanuid == null) {
            //最新的一次推荐链接
            List<ShareOpen> shareOpens = shareOpenService.selectList(new EntityWrapper<ShareOpen>()
                    .eq("mpid", order.getMpid())
                    .eq("ywid", gid)
                    .eq("uid", uid)
                    .orderBy("id", false)
            );
            if (shareOpens != null && shareOpens.size() > 0) {
                ShareOpen shareOpen = shareOpens.get(0);
                if (shareOpen.getZuid() != null) fanuid = shareOpen.getZuid();
                else {
                    User user = redisService.getUserByGuid(shareOpen.getZguid());
                    fanuid = user == null ? null : user.getId();
                }
            }
        }

        logger.info("-------------------------------------------------------shareFan fanuid=" + fanuid);
        if (fanuid == null) {
            return;
        }

        //秒到+非秒到账
        BigDecimal fxe = order.getSharefan();
        User fxuser = userService.selectById(fanuid);

        Goods goods = goodsService.selectById(order.getGid());
        int paytime = FantimeType.payok.getVal();
        //mconfig.getIsMiaotui() 该属性针对现金返佣来说
        //mconfig.getIsAutofan() 该属性针对现金返佣来说
        //直接入账触发点 1：支付成功后；2：确认收货|扫码核销后；3：确认后7天到账&
        //==待实现 3：确认后7天到账&
        //否则先放入待返利中。。。
        boolean nowfan = order.getFantimeType().intValue() == FantimeType.payok.getVal();

        logger.info("------------------------------------------------------shareFan nowfan=" + nowfan);
        // 返佣需要入账做记录
        fanyong(fxuser, fxe, goods.getShareBonusType(), paytime, order, true, nowfan, XftypeEnum.sharefan);

        logger.info("-----------------------------------shareFan over");
    }


    public void zigouFanquan(Order order) {

        logger.info("------------------------------------------------------zigouFanquan come");

        //返现用户
        Long mpid = order.getMpid();
        logger.info("======zigouFan mpid=" + mpid);

        List<OrderGoods> oglist = orderGoodsService.selectList(new EntityWrapper<OrderGoods>()
                .setSqlSelect("oid,gid")
                .eq("oid", order.getId()));
        List<String> gidlist = new ArrayList<String>();
        for (OrderGoods item : oglist) {
            if (item.getGid() != null) gidlist.add(item.getGid().toString());
        }

        if (gidlist.size() == 0) {
            logger.info("-----------------------------------------------gidlist.size()==0");
            return;
        }
        List<Goods> goodslist = goodsService.selectBatchIds(gidlist);
        for (Goods item : goodslist) {
            logger.info("-------------------------------------------------zigouFanquan Goods item=" + JSON.toJSONString(item));

            if (item.getZgfanType() != null && item.getZgfanType().intValue() == 3 && item.getZgfanYwid() != null) {
                int num = item.getZgfanMount();
                Long tplid = item.getZgfanYwid();
                CouponTpl ctpl = couponTplService.selectById(tplid);
                for (int i = 0; i < num; i++) {
                    Coupon coupon = new Coupon();
                    coupon.setIsUnused(1);//未使用
                    coupon.setIsUsed(0);//已使用
                    coupon.setIsForever(ctpl.getIsForever());//永久有效
                    coupon.setIsOutdate(0);//已过期
                    coupon.setState(1);

                    coupon.setMid(order.getMid());
                    coupon.setMpid(order.getMpid());
                    coupon.setUid(order.getUid());
                    coupon.setSid(ctpl.getSid());
                    coupon.setCreatetime(new Date());

                    coupon.setTplid(ctpl.getId());
                    coupon.setType(ctpl.getType());
                    coupon.setName(ctpl.getName());
                    coupon.setSlogo(ctpl.getSlogo());
                    coupon.setSname(ctpl.getSname());
                    coupon.setRemark(ctpl.getRemark());

                    coupon.setCno(StringUtil.getQuanCode(order.getMid()));
                    coupon.setSn(order.getOrderNo());

                    coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                    coupon.setCost(ctpl.getCost());
                    coupon.setUsemin(ctpl.getUsemin());
                    coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                    coupon.insert();
                }

                CouponTpl ctpl2 = new CouponTpl();
                ctpl2.setUse(ctpl.getUse() + num);
                ctpl2.setId(ctpl.getId());
                ctpl2.updateById();
            }
        }

        logger.info("======zigouFanquan over");
    }
}
